/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { Project } from '@ohos/hvigor';
import { FileSet, TaskInputValue } from '@ohos/hvigor';
import fse from 'fs-extra';

import { PackingToolOptions } from '../builder/inner-java-command-builder/packing-tool-options.js';
import { ProcessUtils } from '../utils/process-utils.js';

import { TaskNames } from './common/task-names.js';
import { ProjectTaskService } from './service/project-task-service.js';
import { MakeProjectPackInfo } from './make-project-pack-info.js';
import Task = TaskNames.Task;
import { BasePackAppTask } from './base/base-pack-app-task.js';
import { DuplicateDependencyCheck } from './duplicate-dependency-check.js';
import {ProcessProjectPrivacyProfile} from "./process-project-privacy-profile";

/**
 * 调用打包工具生成pack.res
 *
 * @since 2023/1/13
 */
export class GeneratePackRes extends BasePackAppTask {
  private readonly packResCommand: string[] | undefined;

  declareExecutionCommand(): string {
    return `${this.packResCommand?.toString()}`;
  }

  declareInputs(): Map<string, TaskInputValue> {
    return new Map<string, TaskInputValue>().set('needPackRes', this.needPackRes);
  }

  declareInputFiles(): FileSet {
    const fileSet = new FileSet().addEntry(this.packInfoPath, {
      isDirectory: false,
    });
    if (this.needPackRes) {
      fileSet.addEntry(this.entryCardDir, { isDirectory: true });
    }
    return fileSet;
  }

  declareOutputFiles(): FileSet {
    const fileSet = super.declareOutputFiles();
    if (this.needPackRes) {
      fileSet.addEntry(this.packResPath, { isDirectory: false });
    }
    return fileSet;
  }

  constructor(project: Project, taskService: ProjectTaskService) {
    super(project, taskService, Task.GeneratePackRes);
    if (this.needPackRes) {
      this.packResCommand = (new PackingToolOptions().addCalledJarFile(this.packageTool) as PackingToolOptions)
        .addMode('res')
        .addEntryCardPath(this.entryCardDir)
        .addPackInfoPath(this.packInfoPath)
        .addOutPath(this.packResPath)
        .force(true)
        .build();
    }
  }

  initTaskDepends(): void {
    // 在执行打包packageHap时需要先执行preBuildApp,设置debuggable=false,因此需要保证PreBuildApp任务依赖先注册
    this.dependsOn(DuplicateDependencyCheck.name);
    this.dependsOn(MakeProjectPackInfo.name);
    this.dependsOn(ProcessProjectPrivacyProfile.name);
  }

  protected async doTaskAction(): Promise<void> {
    await this.generatePackRes();
  }

  /**
   * 调用打包工具, 当工程目录下有EntryCard目录时, 生成pack.res用于应用市场上架
   */
  protected async generatePackRes(): Promise<void> {
    if (!this.needPackRes) {
      fse.rmSync(this.packResPath, { force: true });
      return;
    }
    this._log._printDebugCommand('PackRes', this.packResCommand!);
    await new ProcessUtils().execute(this.packResCommand!);
  }
}
